﻿using DevExpress.XtraEditors;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HRM.DICTIONARY.BLL
{
    public class DataController
    {
        public delegate void ShowPercentCompleteDelegate(ProgressBarControl myBarControl,int percent);
        public delegate void ShowMessageDelegate(ProgressBarControl myBarControl, string message);
        private static string _mConnectionString = "data source=.;initial catalog=toro.hrm;persist security info=True;user id=sa;password=123456";
        public string ErrMsg { get; set; }
        public ProgressBarControl progess { get; set; }
        public static string ConnectString
        {
            get
            {
                return _mConnectionString;
            }
            set
            {
                _mConnectionString = value;
            }
        }
        public bool BackupDataBase(string databaseName, string destinationPath)
        {
            try
            {
                SqlConnection.ClearAllPools();
                SqlConnection sqlConnection = new SqlConnection(_mConnectionString);
                sqlConnection.Open();
                ServerConnection serverConnection = new ServerConnection(sqlConnection);
                Server srv = new Server(serverConnection);
                Backup backup = new Backup
                {
                    Action = BackupActionType.Database,
                    Database = databaseName
                };
                backup.Devices.Add(new BackupDeviceItem(destinationPath, DeviceType.File));
                backup.Initialize = true;
                backup.Checksum = true;
                backup.ContinueAfterError = true;
                backup.Incremental = false;
                backup.LogTruncation = BackupTruncateLogType.Truncate;
                backup.PercentComplete += new PercentCompleteEventHandler(backup_PercentComplete);
                backup.Complete += new ServerMessageEventHandler(backup_Complete);
                backup.Information += new ServerMessageEventHandler(backup_Information);
                backup.SqlBackup(srv);
                sqlConnection.Close();
                return true;
            }
            catch (FailedOperationException)
            {
                this.ErrMsg = "Không thể sao lưu dữ liệu.\nChi Tiết:\n\tThư mục sao lưu đã được bảo vệ, vui lòng chọn thư mục khác.";
                return false;
            }
            catch (Exception exception2)
            {
                if (exception2.Message.IndexOf("failed for Server") != -1)
                {
                    this.ErrMsg = "Không thể sao lưu dữ liệu.\nChi Tiết:\n\tThư mục sao lưu đã được bảo vệ, vui lòng chọn thư mục khác.";
                    return false;
                }
                else
                {
                    this.ErrMsg = exception2.Message;
                    return false;
                }
            }
        }
        public bool RestoreDatabase(string backupFilePath, string destinationDatabaseName)
        {
            try
            {
                SqlConnection sqlConnection = new SqlConnection(_mConnectionString);
                sqlConnection.Open();
                ServerConnection serverConnection = new ServerConnection(sqlConnection);
                Server srv = new Server(serverConnection);
                Restore restore = new Restore
                {
                    Database = destinationDatabaseName
                };
                Database database = srv.Databases[destinationDatabaseName];
                if (database != null)
                {
                    srv.KillAllProcesses(destinationDatabaseName);
                }
                restore.Action = RestoreActionType.Database;
                restore.Devices.AddDevice(backupFilePath, DeviceType.File);
                restore.ReplaceDatabase = true;
                restore.PercentCompleteNotification = 10;
                restore.PercentComplete += new PercentCompleteEventHandler(this.restore_PercentComplete);
                restore.Complete += new ServerMessageEventHandler(this.restore_Complete);
                restore.Information += new ServerMessageEventHandler(this.restore_Information);
                restore.SqlRestore(srv);
                sqlConnection.Close();
                return true;
            }
            catch (FailedOperationException)
            {
                this.ErrMsg = "Không thể phục hồi dữ liệu.\nChi Tiết:\n\tThư mục sao lưu đã được bảo vệ, vui lòng chọn thư mục khác.";
                return false;
            }
            catch (Exception exception2)
            {
                if (exception2.Message.IndexOf("failed for Server") != -1)
                {
                    this.ErrMsg = "Không thể phục hồi dữ liệu.\nChi Tiết:\n\tThư mục phục hồi đã được bảo vệ, vui lòng chọn thư mục khác.";
                    return false;
                }
                else
                {
                    this.ErrMsg = exception2.Message;
                    return false;
                }
            }
        }
        public void backup_PercentComplete(object sender, PercentCompleteEventArgs e)
        {
            progess.EditValue = e.Percent;
            progess.Update();
        }
        public void backup_Information(object sender, ServerMessageEventArgs e)
        {
            ErrMsg = e.Error.Message;
            progess.Refresh();
        }
        public void backup_Complete(object sender, ServerMessageEventArgs e)
        {
            ErrMsg = "Backup complete";
            progess.Dispose();
        }
        public void restore_PercentComplete(object sender, PercentCompleteEventArgs e)
        {
            progess.EditValue = e.Percent;
            progess.Update();
        }
        public void restore_Information(object sender, ServerMessageEventArgs e)
        {
            ErrMsg = e.Error.Message;
            progess.Refresh();
        }
        public void restore_Complete(object sender, ServerMessageEventArgs e)
        {
            ErrMsg = "Restore complete";
            progess.Dispose();
        }
        public void ShowPercentComplete(int percent)
        {
            progess.EditValue = percent;
        }
        public void ShowMessage(string message)
        {
            ErrMsg = message;
        }
    }
}
